package com.qc.wintrax.utils;

import android.text.TextUtils;

import com.qc.wintrax.model.EventInfo;

import java.security.acl.Group;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/8/26.
 */

public class LocalGroupSearch {

    /**
     * 按群号-群名拼音搜索
     *
     * @param str
     */
    public static ArrayList<EventInfo> searchGroup(CharSequence str, ArrayList<EventInfo> allContacts) {
        ArrayList<EventInfo> groupList = new ArrayList<EventInfo>();
        // 如果搜索条件以0 1 +开头则按号码搜索
        CharacterParser finder = CharacterParser.getInstance();
        String result = "";
        for (EventInfo group : allContacts) {
            // 先将输入的字符串转换为拼音
            finder.setResource(str.toString());
            result = finder.getSpelling();
            if (contains(group, result)) {
                groupList.add(group);
            } else if ((group.getTitle() + "").contains(str)) {
                groupList.add(group);
            }
        }
        return groupList;
    }


    private static boolean contains(EventInfo group, String search) {
        if (TextUtils.isEmpty(group.getTitle())) {
            return false;
        }

        boolean flag = false;

        if (!flag) { // 如果简拼已经找到了，就不使用全拼了
            // 全拼匹配
            CharacterParser finder = CharacterParser.getInstance();
            finder.setResource(getGroupName(group));
            // 不区分大小写
            Pattern pattern2 = Pattern
                    .compile(search, Pattern.CASE_INSENSITIVE);
            Matcher matcher2 = pattern2.matcher(finder.getSpelling());
            flag = matcher2.find();
        }

        return flag;
    }

    private static String getGroupName(EventInfo group) {
        String strName = null;
        if (!TextUtils.isEmpty(group.getTitle())) {
            strName = group.getTitle();
        } else {
            strName = "";
        }

        return strName;
    }
}